/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.controller;

import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Strings;
import com.je.common.base.controller.CommonPlatformController;
import com.je.common.base.result.BaseRespResult;
import com.je.meta.service.SqlTemplateService;
import net.sf.jsqlparser.JSQLParserException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/je/common/script/sql")
public class SqlTemplateController extends CommonPlatformController {

    private static final String DEFAULT_FROTEND_ENTRY_TYPE = "JS";
    private static final String DEFAULT_FROTEND_ENTRY_NAME = "前台触发";

    private static final String UNKNOWN_SOURCE = "未知";

    @Autowired
    private SqlTemplateService sqlTemplateService;

    private String getDesc(HttpServletRequest request) {
        String desc = request.getParameter("desc");
        if (Strings.isNullOrEmpty(desc)) {
            desc = getStringParameterByContext("desc");
        }
        return desc;
    }

    @RequestMapping(value = "/insert", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult insert(HttpServletRequest request) {
        String templateCode = request.getParameter("templateCode");
        String pd = request.getParameter("projectCode");
        String desc = getDesc(request);
        String entryType = DEFAULT_FROTEND_ENTRY_TYPE;
        String entryName = DEFAULT_FROTEND_ENTRY_NAME;
        if (Strings.isNullOrEmpty(templateCode)) {
            return BaseRespResult.errorResult("请指定SQL模板！");
        }
        if (Strings.isNullOrEmpty(pd)) {
            return BaseRespResult.errorResult("请指定模板所属服务！");
        }

        Map<String, Object> params = fetchParams(request);
        if (params.containsKey("entryType")) {
            entryType = params.get("entryType").toString();
            entryName = params.get("entryName").toString();
        }

        if (Strings.isNullOrEmpty(desc)) {
            desc = UNKNOWN_SOURCE;
        }

        try {
            int result = sqlTemplateService.insert(entryType, entryName, desc, pd, templateCode, params);
            return BaseRespResult.successResult(result > 0 ? true : false);
        } catch (JSQLParserException e) {
            e.printStackTrace();
            return BaseRespResult.errorResult(e.getMessage());
        }
    }

    @RequestMapping(value = "/insertAndInit", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult insertAndInit(HttpServletRequest request) {
        String templateCode = request.getParameter("templateCode");
        String pd = request.getParameter("projectCode");
        String desc = getDesc(request);
        String entryType = DEFAULT_FROTEND_ENTRY_TYPE;
        String entryName = DEFAULT_FROTEND_ENTRY_NAME;
        if (Strings.isNullOrEmpty(templateCode)) {
            return BaseRespResult.errorResult("请指定SQL模板！");
        }
        if (Strings.isNullOrEmpty(pd)) {
            return BaseRespResult.errorResult("请指定模板所属服务！");
        }

        Map<String, Object> params = fetchParams(request);
        if (params.containsKey("entryType")) {
            entryType = params.get("entryType").toString();
            entryName = params.get("entryName").toString();
        }

        if (Strings.isNullOrEmpty(desc)) {
            desc = UNKNOWN_SOURCE;
        }

        try {
            int result = sqlTemplateService.insertAndInit(entryType, entryName, desc, pd, templateCode, params);
            return BaseRespResult.successResult(result > 0 ? true : false);
        } catch (JSQLParserException e) {
            e.printStackTrace();
            return BaseRespResult.errorResult(e.getMessage());
        }
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult update(HttpServletRequest request) {
        String templateCode = request.getParameter("templateCode");
        String pd = request.getParameter("projectCode");
        String desc = getDesc(request);
        String entryType = DEFAULT_FROTEND_ENTRY_TYPE;
        String entryName = DEFAULT_FROTEND_ENTRY_NAME;
        if (Strings.isNullOrEmpty(templateCode)) {
            return BaseRespResult.errorResult("请指定SQL模板！");
        }
        if (Strings.isNullOrEmpty(pd)) {
            return BaseRespResult.errorResult("请指定模板所属服务！");
        }

        Map<String, Object> params = fetchParams(request);
        if (params.containsKey("entryType")) {
            entryType = params.get("entryType").toString();
            entryName = params.get("entryName").toString();
        }

        if (Strings.isNullOrEmpty(desc)) {
            desc = UNKNOWN_SOURCE;
        }

        try {
            int result = sqlTemplateService.update(entryType, entryName, desc, pd, templateCode, params);
            return BaseRespResult.successResult(result > 0 ? true : false);
        } catch (JSQLParserException e) {
            e.printStackTrace();
            return BaseRespResult.errorResult(e.getMessage());
        }
    }

    @RequestMapping(value = "/delete", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult delete(HttpServletRequest request) {
        String templateCode = request.getParameter("templateCode");
        String pd = request.getParameter("projectCode");
        String desc = getDesc(request);
        String entryType = DEFAULT_FROTEND_ENTRY_TYPE;
        String entryName = DEFAULT_FROTEND_ENTRY_NAME;
        if (Strings.isNullOrEmpty(templateCode)) {
            return BaseRespResult.errorResult("请指定SQL模板！");
        }
        if (Strings.isNullOrEmpty(pd)) {
            return BaseRespResult.errorResult("请指定模板所属服务！");
        }
        Map<String, Object> params = fetchParams(request);
        if (params.containsKey("entryType")) {
            entryType = params.get("entryType").toString();
            entryName = params.get("entryName").toString();
        }

        if (Strings.isNullOrEmpty(desc)) {
            desc = UNKNOWN_SOURCE;
        }

        try {
            int result = sqlTemplateService.delete(entryType, entryName, desc, pd, templateCode, params);
            return BaseRespResult.successResult(result > 0 ? true : false);
        } catch (JSQLParserException e) {
            e.printStackTrace();
            return BaseRespResult.errorResult(e.getMessage());
        }
    }

    @RequestMapping(value = "/select", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult select(HttpServletRequest request) {
        String templateCode = request.getParameter("templateCode");
        String pd = request.getParameter("projectCode");
        String desc = getDesc(request);
        String entryType = DEFAULT_FROTEND_ENTRY_TYPE;
        String entryName = DEFAULT_FROTEND_ENTRY_NAME;

        if (Strings.isNullOrEmpty(templateCode)) {
            return BaseRespResult.errorResult("请指定SQL模板！");
        }
        if (Strings.isNullOrEmpty(pd)) {
            return BaseRespResult.errorResult("请指定模板所属服务！");
        }

        Map<String, Object> params = fetchParams(request);
        if (params.containsKey("entryType")) {
            entryType = params.get("entryType").toString();
            entryName = params.get("entryName").toString();
        }

        if (Strings.isNullOrEmpty(desc)) {
            desc = UNKNOWN_SOURCE;
        }

        try {
            List<Map<String, Object>> result = sqlTemplateService.select(entryType, entryName, desc, pd, templateCode, params);
            return BaseRespResult.successResult(result);
        } catch (JSQLParserException e) {
            e.printStackTrace();
            return BaseRespResult.errorResult(e.getMessage());
        }
    }

    private Map<String, Object> fetchParams(HttpServletRequest request) {
        Map<String, Object> params = new HashMap<>();
        Enumeration<String> paramEnu = request.getParameterNames();
        String paramName;
        while (paramEnu.hasMoreElements()) {
            paramName = paramEnu.nextElement();
            params.put(paramName, request.getParameter(paramName));
        }

        Enumeration<String> attrEnu = request.getAttributeNames();
        while (attrEnu.hasMoreElements()) {
            paramName = attrEnu.nextElement();
            params.put(paramName, request.getParameter(paramName));
        }

        //获取流程调用过程的业务bean对象
        String workFlowBeanStr = getStringParameterByContext("workFlowBean");
        if (!Strings.isNullOrEmpty(workFlowBeanStr)) {
            params.put("entryType", "WF");
            params.put("entryName", "流程触发");
            JSONObject jsonObject = JSONObject.parseObject(workFlowBeanStr);
            for (String key : jsonObject.keySet()) {
                params.put(key, jsonObject.get(key));
            }
        }
        return params;
    }

}
